/**
 * 日志编辑器 - 处理日志的添加和删除功能
 */
class DiaryEditor {
  constructor() {
    this.uploadManager = new UploadManager();
    this.config = null;
    this.initUI();
    this.loadConfig();
    this.setupEventListeners();
  }

  /**
   * 加载配置数据
   */
  async loadConfig() {
    try {
      this.config = await DataLoader.loadConfig();
    } catch (error) {
      console.error('加载配置数据失败:', error);
    }
  }

  /**
   * 初始化UI元素
   */
  initUI() {
    // 在页面中添加编辑控件
    const diaryContainer = document.querySelector('.diary-entries');
    if (!diaryContainer) return;

    // 添加新日志按钮
    const addButtonContainer = document.createElement('div');
    addButtonContainer.className = 'add-diary-btn-container text-center my-4';
    addButtonContainer.innerHTML = `
      <button id="addDiaryBtn" class="btn btn-primary">
        <i class="fas fa-plus"></i> 添加新日志
      </button>
    `;
    diaryContainer.parentNode.insertBefore(addButtonContainer, diaryContainer);

    // 添加日志表单模态框
    const modalHTML = `
      <div class="modal fade" id="diaryFormModal" tabindex="-1" aria-labelledby="diaryFormModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title" id="diaryFormModalLabel">添加新日志</h5>
              <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
            </div>
            <div class="modal-body">
              <form id="diaryForm">
                <div class="mb-3">
                  <label for="diaryTitle" class="form-label">日志标题</label>
                  <input type="text" class="form-control" id="diaryTitle" required>
                </div>
                <div class="mb-3">
                  <label for="diaryDate" class="form-label">日期</label>
                  <input type="date" class="form-control" id="diaryDate" required>
                </div>
                <div class="mb-3">
                  <label for="diaryAuthor" class="form-label">作者</label>
                  <select class="form-select" id="diaryAuthor" required>
                    <option value="">选择作者...</option>
                    <option value="boy">小明</option>
                    <option value="girl">小红</option>
                  </select>
                </div>
                <div class="mb-3">
                  <label for="diaryMood" class="form-label">心情</label>
                  <select class="form-select" id="diaryMood" required>
                    <option value="">选择心情...</option>
                    <option value="happy">开心</option>
                    <option value="sad">难过</option>
                    <option value="love">甜蜜</option>
                    <option value="angry">生气</option>
                    <option value="neutral">平静</option>
                  </select>
                </div>
                <div class="mb-3">
                  <label for="diaryContent" class="form-label">日志内容</label>
                  <textarea class="form-control" id="diaryContent" rows="6" required></textarea>
                  <small class="form-text text-muted">每段内容用换行符分隔，将被显示为单独的段落。</small>
                </div>
                <div class="mb-3">
                  <label class="form-label">照片</label>
                  <div class="d-flex align-items-center">
                    <input type="file" class="form-control me-2" id="diaryPhotos" accept="image/*" multiple>
                    <button type="button" class="btn btn-outline-primary" id="addDiaryPhotosBtn">
                      <i class="fas fa-plus"></i>
                    </button>
                  </div>
                  <div class="row mt-2" id="diaryPhotosPreview"></div>
                </div>
                <div id="diary-photos-container">
                  <!-- 这里将动态添加照片相关字段 -->
                </div>
              </form>
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
              <button type="button" class="btn btn-primary" id="saveDiaryBtn">保存日志</button>
            </div>
          </div>
        </div>
      </div>

      <!-- 删除确认模态框 -->
      <div class="modal fade" id="deleteDiaryConfirmModal" tabindex="-1" aria-labelledby="deleteDiaryConfirmModalLabel" aria-hidden="true">
        <div class="modal-dialog">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title" id="deleteDiaryConfirmModalLabel">确认删除</h5>
              <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
            </div>
            <div class="modal-body">
              确定要删除这篇日志吗？此操作不可撤销。
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
              <button type="button" class="btn btn-danger" id="confirmDeleteDiaryBtn">删除</button>
            </div>
          </div>
        </div>
      </div>
    `;

    // 将模态框添加到页面
    document.body.insertAdjacentHTML('beforeend', modalHTML);

    // 为每个日志添加编辑和删除按钮
    this.addDiaryControls();
  }

  /**
   * 为日志添加编辑和删除控件
   */
  addDiaryControls() {
    const diaryCards = document.querySelectorAll('.diary-card');
    
    diaryCards.forEach(card => {
      // 获取日志ID
      const diaryId = card.dataset.id;
      if (!diaryId) return;
      
      // 添加控制按钮
      const controlsContainer = document.createElement('div');
      controlsContainer.className = 'diary-controls position-absolute top-0 end-0 m-2';
      controlsContainer.innerHTML = `
        <button class="btn btn-sm btn-danger delete-diary-btn" data-id="${diaryId}">
          <i class="fas fa-trash"></i>
        </button>
      `;
      
      // 设置相对定位，以便正确定位控件
      const header = card.querySelector('.diary-header');
      if (header) {
        header.style.position = 'relative';
        header.appendChild(controlsContainer);
      }
    });
  }

  /**
   * 设置事件监听器
   */
  setupEventListeners() {
    // 添加日志按钮点击事件
    const addDiaryBtn = document.getElementById('addDiaryBtn');
    if (addDiaryBtn) {
      addDiaryBtn.addEventListener('click', () => {
        // 重置表单
        document.getElementById('diaryForm').reset();
        document.getElementById('diaryPhotosPreview').innerHTML = '';
        document.getElementById('diary-photos-container').innerHTML = '';
        
        // 设置默认日期为今天
        document.getElementById('diaryDate').valueAsDate = new Date();
        
        // 显示模态框
        const modal = new bootstrap.Modal(document.getElementById('diaryFormModal'));
        modal.show();
      });
    }

    // 上传日志照片预览
    const diaryPhotos = document.getElementById('diaryPhotos');
    const addDiaryPhotosBtn = document.getElementById('addDiaryPhotosBtn');
    if (diaryPhotos && addDiaryPhotosBtn) {
      addDiaryPhotosBtn.addEventListener('click', () => {
        const files = diaryPhotos.files;
        if (files.length === 0) return;
        
        // 添加照片预览和描述输入框
        this.addDiaryPhotoInputs(files);
        
        // 清空文件输入框，以便再次选择文件
        diaryPhotos.value = '';
      });
    }

    // 保存日志按钮点击事件
    const saveDiaryBtn = document.getElementById('saveDiaryBtn');
    if (saveDiaryBtn) {
      saveDiaryBtn.addEventListener('click', () => {
        this.saveDiary();
      });
    }

    // 设置删除日志按钮的事件委托
    document.addEventListener('click', (event) => {
      if (event.target.closest('.delete-diary-btn')) {
        const btn = event.target.closest('.delete-diary-btn');
        const diaryId = btn.dataset.id;
        
        // 设置当前要删除的日志ID
        document.getElementById('confirmDeleteDiaryBtn').dataset.id = diaryId;
        
        // 显示确认删除模态框
        const modal = new bootstrap.Modal(document.getElementById('deleteDiaryConfirmModal'));
        modal.show();
      }
    });

    // 确认删除按钮点击事件
    const confirmDeleteDiaryBtn = document.getElementById('confirmDeleteDiaryBtn');
    if (confirmDeleteDiaryBtn) {
      confirmDeleteDiaryBtn.addEventListener('click', () => {
        const diaryId = confirmDeleteDiaryBtn.dataset.id;
        this.deleteDiary(diaryId);
      });
    }
  }

  /**
   * 添加日志照片输入框
   * @param {FileList} files - 选择的照片文件
   */
  addDiaryPhotoInputs(files) {
    const container = document.getElementById('diary-photos-container');
    const photosPreview = document.getElementById('diaryPhotosPreview');
    
    for (let i = 0; i < files.length; i++) {
      const file = files[i];
      const photoId = Date.now() + i;
      
      // 添加预览
      const previewCol = document.createElement('div');
      previewCol.className = 'col-md-3 mb-3';
      previewCol.dataset.photoId = photoId;
      
      const reader = new FileReader();
      reader.onload = (e) => {
        previewCol.innerHTML = `
          <div class="position-relative">
            <img src="${e.target.result}" class="img-thumbnail w-100" alt="照片预览">
            <button type="button" class="btn btn-sm btn-danger position-absolute top-0 end-0 m-1 remove-diary-photo" data-photo-id="${photoId}">
              <i class="fas fa-times"></i>
            </button>
          </div>
        `;
      };
      reader.readAsDataURL(file);
      
      photosPreview.appendChild(previewCol);
      
      // 添加照片表单字段
      const photoFieldset = document.createElement('fieldset');
      photoFieldset.className = 'mb-3 diary-photo-fieldset';
      photoFieldset.dataset.photoId = photoId;
      photoFieldset.innerHTML = `
        <input type="hidden" name="diaryPhotoFile_${photoId}" value="${file.name}" class="diary-photo-file">
        <div class="mb-3">
          <label class="form-label">照片描述</label>
          <input type="text" class="form-control diary-photo-description" required>
        </div>
      `;
      
      container.appendChild(photoFieldset);
      
      // 添加删除照片的事件监听
      setTimeout(() => {
        const removeBtn = document.querySelector(`.remove-diary-photo[data-photo-id="${photoId}"]`);
        if (removeBtn) {
          removeBtn.addEventListener('click', () => {
            // 删除预览和表单字段
            const preview = document.querySelector(`.col-md-3[data-photo-id="${photoId}"]`);
            const fieldset = document.querySelector(`.diary-photo-fieldset[data-photo-id="${photoId}"]`);
            
            if (preview) preview.remove();
            if (fieldset) fieldset.remove();
          });
        }
      }, 100);
    }
  }

  /**
   * 保存日志
   */
  async saveDiary() {
    try {
      const titleInput = document.getElementById('diaryTitle');
      const dateInput = document.getElementById('diaryDate');
      const authorInput = document.getElementById('diaryAuthor');
      const moodInput = document.getElementById('diaryMood');
      const contentInput = document.getElementById('diaryContent');
      
      // 表单验证
      if (!titleInput.value || !dateInput.value || !authorInput.value || !moodInput.value || !contentInput.value) {
        alert('请填写所有必填字段');
        return;
      }
      
      // 显示加载状态
      const saveBtn = document.getElementById('saveDiaryBtn');
      const originalText = saveBtn.innerHTML;
      saveBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 保存中...';
      saveBtn.disabled = true;
      
      // 1. 上传照片
      const photoFieldsets = document.querySelectorAll('.diary-photo-fieldset');
      const photos = [];
      
      for (const fieldset of photoFieldsets) {
        const photoId = fieldset.dataset.photoId;
        const descriptionInput = fieldset.querySelector('.diary-photo-description');
        
        if (!descriptionInput.value) {
          alert('请填写所有照片的描述');
          saveBtn.innerHTML = originalText;
          saveBtn.disabled = false;
          return;
        }
        
        // 获取对应的文件
        const previewEl = document.querySelector(`.col-md-3[data-photo-id="${photoId}"]`);
        if (previewEl) {
          const imgSrc = previewEl.querySelector('img').src;
          
          // 如果是base64格式，表示是新上传的文件
          if (imgSrc.startsWith('data:image')) {
            // 查找对应的文件
            const fileName = fieldset.querySelector('.diary-photo-file').value;
            let photoFile = null;
            
            // 从原始文件输入中查找匹配的文件
            const fileInput = document.getElementById('diaryPhotos');
            for (let i = 0; i < fileInput.files.length; i++) {
              if (fileInput.files[i].name === fileName) {
                photoFile = fileInput.files[i];
                break;
              }
            }
            
            if (photoFile) {
              // 上传照片
              const photoUploadResult = await this.uploadManager.uploadImage(photoFile, 'diary');
              
              photos.push({
                src: photoUploadResult.filePath,
                description: descriptionInput.value
              });
            }
          }
        }
      }
      
      // 2. 构建日志数据
      const diaryData = {
        title: titleInput.value,
        date: dateInput.value,
        author: authorInput.value,
        authorName: authorInput.value === 'boy' ? this.config?.couple?.boy?.name || '小明' : this.config?.couple?.girl?.name || '小红',
        authorAvatar: authorInput.value === 'boy' ? this.config?.couple?.boy?.avatar || 'img/couples/boy.jpg' : this.config?.couple?.girl?.avatar || 'img/couples/girl.jpg',
        mood: moodInput.value,
        content: contentInput.value.split('\n').filter(paragraph => paragraph.trim() !== ''),
        photos: photos,
        likes: 0,
        comments: []
      };
      
      // 3. 保存日志数据
      const result = await this.uploadManager.addDiary(diaryData);
      
      // 4. 处理结果
      if (result.success) {
        alert('日志添加成功');
        
        // 关闭模态框
        const modal = bootstrap.Modal.getInstance(document.getElementById('diaryFormModal'));
        modal.hide();
        
        // 刷新页面以显示新日志
        window.location.reload();
      } else {
        throw new Error(result.message || '添加日志失败');
      }
    } catch (error) {
      console.error('保存日志出错:', error);
      alert(`添加日志失败: ${error.message}`);
      
      // 恢复按钮状态
      const saveBtn = document.getElementById('saveDiaryBtn');
      saveBtn.innerHTML = '<i class="fas fa-save"></i> 保存日志';
      saveBtn.disabled = false;
    }
  }

  /**
   * 删除日志
   * @param {string} diaryId - 要删除的日志ID
   */
  async deleteDiary(diaryId) {
    try {
      // 显示加载状态
      const confirmBtn = document.getElementById('confirmDeleteDiaryBtn');
      const originalText = confirmBtn.innerHTML;
      confirmBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 删除中...';
      confirmBtn.disabled = true;
      
      // 调用删除API
      const result = await this.uploadManager.deleteDiary(diaryId);
      
      // 处理结果
      if (result.success) {
        // 关闭模态框
        const modal = bootstrap.Modal.getInstance(document.getElementById('deleteDiaryConfirmModal'));
        modal.hide();
        
        // 从页面中移除日志
        const diaryCard = document.querySelector(`.diary-card[data-id="${diaryId}"]`);
        if (diaryCard) {
          diaryCard.remove();
        } else {
          // 如果找不到对应元素，刷新页面
          window.location.reload();
        }
        
        alert('日志已成功删除');
      } else {
        throw new Error(result.message || '删除日志失败');
      }
    } catch (error) {
      console.error('删除日志出错:', error);
      alert(`删除日志失败: ${error.message}`);
      
      // 恢复按钮状态
      const confirmBtn = document.getElementById('confirmDeleteDiaryBtn');
      confirmBtn.innerHTML = originalText;
      confirmBtn.disabled = false;
    }
  }
}

// 当文档加载完成时初始化编辑器
document.addEventListener('DOMContentLoaded', () => {
  // 检查是否在日志页面
  if (document.querySelector('.diary-entries')) {
    new DiaryEditor();
  }
}); 